<template>
  <div>
    <Modal
      :value="modalState"
      :title="title"
      :loading="loading"
      ok-text="确认兑换"
      @on-ok="handleSubmit"
      @on-cancel="cancel"
      width="30%">
      <Form
        ref="exchangeModal"
        :model="row"
        :rules="ruleInline"
        style="width: 100%; margin-left: 50px;"
        :label-width="100">
        <FormItem prop="gname" style="width: 300px;" label="兑换商品名称：">
          <div>{{row.gname}}</div>
        </FormItem>
        <FormItem prop="code" style="width: 300px;" label="兑换码：">
          <Input type="text" v-model="row.code" placeholder="请输入兑换码" />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import {
  mapActions,
  mapState
} from 'vuex'
export default {
  name: 'ExchangeModal',
  data () {
    return {
      title: '',
      loading: true,
      ruleInline: {
        code: [
          {
            required: true,
            message: '兑换码不能为空',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  updated () {
    this.title = '兑换商品'
  },
  computed: {
    ...mapState({
      row: state => state.exchange.row,
      modalState: state => state.modal.modalState
    })
  },
  methods: {
    ...mapActions(['updateModalState']),
    changeLoading () {
      this.loading = false
      this.$nextTick(() => {
        this.loading = true
      })
    },
    handleSubmit () {
      this.$refs.exchangeModal.validate((valid) => {
        if (!valid) {
          return this.changeLoading()
        }
        this.$emit('exchange-valid', {
          id: this.row.id,
          code: this.row.code
        })
      })
    },
    cancel () {
      this.updateModalState(false)
      this.$refs['exchangeModal'].resetFields()
    }
  }
}
</script>
